package com.sjq.common.web;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;



import com.sjq.common.dao.UserDao;
import com.sjq.common.entity.LoginAccount;
import com.sjq.common.entity.User;

/**
 * 用户登录Session信息
 */
public class SessionUserHelper {
    public static final String USER_TOKEN = "user_token";
    private static final String SESSION_KEY = "account";
    private SessionHelper sessionHelper = null;
    private String userToken = "";

    private SessionUserHelper(HttpSession session) {
        sessionHelper = SessionHelper.create(session);
    }

    private SessionUserHelper(HttpSession session, String token) {
        if (StringUtils.isNoneEmpty(token)) {
            userToken = token.trim();
        }
        sessionHelper = SessionHelper.create(session);
    }

    private static final Logger LOG = LoggerFactory.getLogger(SessionUserHelper.class);

    public static SessionUserHelper create(HttpServletRequest request) {
        String token = request.getParameter(USER_TOKEN);
        return new SessionUserHelper(request.getSession(), token);
    }

    public static SessionUserHelper createBySession(HttpSession session) {
        return new SessionUserHelper(session);
    }

    /**
     * 获取用户登录信息
     *
     * @return
     */
    public LoginAccount getLoginAccount() {
        LoginAccount account = getLoginAccountCore();
        if (account == null) {
            LOG.error("用户登录信息在 session 中过期！！！");
            throw new RuntimeException("用户登录信息在 session 中过期！！！");
        }
        return account;
    }

    private LoginAccount getLoginAccountCore() {

        LoginAccount sessionAccount = sessionHelper.getAttribute(SESSION_KEY, LoginAccount.class);
        // 没有 token
        if (StringUtils.isEmpty(this.userToken)) {
            return sessionAccount;
        }
        // session 失效
        if (sessionAccount == null) {
            LOG.debug(String.format("use token[token=%s] refresh session account info because not find account info.", this.userToken));
            return refreshSessionAccountInfoByToken(this.userToken);
        }

        if ( !sessionAccount.getAccountId().equals(this.userToken)){
            LOG.debug(String.format("use token[token=%s] refresh session account info because session token changed.", this.userToken));
            return refreshSessionAccountInfoByToken(this.userToken);
        }

        return sessionAccount;
    }


    private LoginAccount refreshSessionAccountInfoByToken(String token) {

        ServletContext servletContext = this.sessionHelper.getServletContext();
        ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
        UserDao dao = (UserDao) appContext.getBean("userDao");
        User user = dao.getUserByAccount(token);

        LoginAccount accInfo = null;
        if ( ! user.isEmpty() ){
           // accInfo = new LoginAccount(user.getJH(),user.getYHM(),
                  // user.getXM(),user.getUserIp(),user.getROLEDM(),user.getDWBM(),user.getDWMC(),user.getLXFS());
            
        	accInfo=new LoginAccount(user.getJH(), user.getYHM(), user.getXM(),
        			user.getROLEDM(), user.getDWBM(), user.getDWMC(), user.getUserIp(), user.getLXFS());
        }else{
            LOG.debug(String.format("use token[token=%s] fail not token in server.", this.userToken));
        }

        this.clearSession();
        if (accInfo != null) {
            this.saveToSession(accInfo);
        }

        return accInfo;
    }

    /**
     * 检测是否登录
     *
     * @return 已登录返回 true
     */
    public boolean checkLoginSuccess() {
        LoginAccount account = getLoginAccountCore();
        return (account != null);
    }

    /**
     * 保顾虑账号信息到Session
     *
     * @param account
     */
    public void saveToSession(LoginAccount account) {
        if (account == null) return;

        sessionHelper.setAttribute(SESSION_KEY, account);
    }

    /**
     * 清理Session中的登录用户账户信息
     */
    public void clearSession() {
        sessionHelper.removeAttribute(SESSION_KEY);
    }
}
